import sys
from datetime import datetime
import re


def is_valid_date(date_str, start, end):
    """判断日期字符串是否合法"""  
    date_int = int(date_str)
    if date_int < start or date_int >= end:
        return False

    try:
        datetime.strptime(date_str, "%Y%m%d")
        return True
    except Exception:
        return False


def find_my_date(my_date_str):
    pi = None
    with open("pi.txt") as f:
        pi = f.read()

    date_format = "%Y%m%d"
    nearest_pos = None
    my_date = datetime.strptime(my_date_str, date_format)
    delta_days = sys.maxsize

    for pos in range(0, len(pi) - 8):
        date_str = pi[pos:pos + 8]

        if is_valid_date(date_str, 19800101, 20010101):
            print(pos, date_str)

            tmp_date = datetime.strptime(date_str, date_format)
            tmp_delta_days = abs((tmp_date - my_date).days)
            if tmp_delta_days < delta_days:
                delta_days = tmp_delta_days
                nearest_pos = pos

    print("nearest date:", nearest_pos, pi[nearest_pos:nearest_pos + 8])


def find_years():
    pi = None
    with open("pi.txt") as f:
        pi = f.read()

    re_str = "(19[6-9][0-9]|20[0-1][0-9]|202[0-1])"
    years = re.findall(re_str, pi)
    for item in years:
        print(item)


if __name__ == '__main__':
    find_my_date("19920116")
    find_years()